//
//  HiAugmentedWorldViewController.m
//  HiAugmentedWorld
//
//  Created by Jonathan Saggau on 4/12/10.
//  Copyright Sounds Broken inc. 2010. All rights reserved.
//

#import "HiAugmentedWorldViewController.h"
#import "LocationTools.h"

@implementation HiAugmentedWorldViewController

-(void)viewDidLoad
{
	NSLog(@"locations: %@", [LocationTools locations]);
    [super viewDidLoad];
    picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.showsCameraControls = NO;
    picker.navigationBarHidden = YES;
    
    picker.wantsFullScreenLayout = YES;
    
    //1:1.124.. = aspect ratio of the screen
    picker.cameraViewTransform = CGAffineTransformScale(picker.cameraViewTransform, 1.0f, 1.12412f);
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self presentModalViewController:picker animated:NO];

	CGRect viewFrame = self.view.frame;
    viewFrame.origin.x = viewFrame.origin.y = 0.0;
    UIView *overlayView = [[UIView alloc] initWithFrame:viewFrame];
	/*
	
	// Commented this out because I haven't figured out what I want to do with it yet.
	 
    anglesLabel = [[UILabel alloc] initWithFrame:CGRectMake(10., 360., 300., 30.)];
    [anglesLabel setText:@"Hello augmented world!"];
    [anglesLabel setBackgroundColor:[UIColor clearColor]];
    [anglesLabel setTextColor:[UIColor whiteColor]];
    [anglesLabel setFont:[UIFont boldSystemFontOfSize:12]];
    
    marriotLabel = [[UILabel alloc] initWithFrame:CGRectMake(10., 390., 300., 30.)];
    [marriotLabel setText:@"Hello augmented world!"];
    [marriotLabel setBackgroundColor:[UIColor clearColor]];
    [marriotLabel setTextColor:[UIColor whiteColor]];
    [marriotLabel setFont:[UIFont boldSystemFontOfSize:12]];    
    
    [overlayView addSubview:anglesLabel];
    [overlayView addSubview:marriotLabel];
    [overlayView bringSubviewToFront:anglesLabel];
    [overlayView bringSubviewToFront:marriotLabel];
	 */
    // Load the image to show in the overlay:
	NSArray *locations = [LocationTools locations];
	NSMutableArray *tempViews = [NSMutableArray arrayWithCapacity:[locations count]];
	for (NSDictionary *locationInfo in locations) {
		UIImage *overlayGraphic = [UIImage imageNamed:[locationInfo objectForKey:@"image"]];
		UIView *markerView;
		if (overlayGraphic == nil) {
			// Create a text image?
			UILabel *markerLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 100, 100, 30)];
			markerLabel.textColor = [UIColor whiteColor];
			markerLabel.backgroundColor = [UIColor redColor];
			markerLabel.adjustsFontSizeToFitWidth = YES;
			markerLabel.textAlignment = UITextAlignmentCenter;
			markerLabel.text = [locationInfo objectForKey:@"name"];
			markerView = markerLabel;
		} else {
			markerView = [[UIImageView alloc] initWithImage:overlayGraphic];
			markerView.frame = CGRectMake(30, 100, overlayGraphic.size.width, overlayGraphic.size.height);
		}
		[tempViews addObject:markerView];
		[overlayView addSubview:markerView];
		[markerView release];
	}
	overlayGraphicViews = [tempViews copy];
    picker.cameraOverlayView = overlayView;
    [overlayView release];
    
    [[UIAccelerometer sharedAccelerometer] setDelegate:self];
    locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager setDelegate:self];
    [locationManager startUpdatingHeading];
    [locationManager startUpdatingLocation];
}

- (void)updateUI
{
	NSArray *locations = [LocationTools locations];
	for (int i=0; i<[locations count]; i++) {
		NSDictionary *location = [locations objectAtIndex:i];
		CLLocation *siteLication = [location objectForKey:@"location"];
		float directionToSite = [[LocationTools class] angleFromCoordinate:[self.currentLocation coordinate] toCoordinate:[siteLication coordinate]];
		CLLocationDistance dist = [self.currentLocation getDistanceFrom:siteLication];

	    double deltaAlt = [siteLication altitude] - [self.currentLocation altitude];
		
		//verticalAccuracy of -1 == invalid
		if ([self.currentLocation verticalAccuracy] < 0)
		{
			deltaAlt = 0;
		}

	    double vertAngleToSite = atan2(deltaAlt, dist);
		/*
		[marriotLabel setText:[NSString stringWithFormat:@"DirHotel:%5.1f Dist: %5f VertAngle: %f", 
							   directionToMarriott * (180.0 / M_PI), dist, vertAngleToMarriott * (180.0 / M_PI)]];
		
		[anglesLabel setText: [NSString stringWithFormat:@"Horizon H-Angle:%5.1f V-Angle:%5.1f Heading:%5.1f", 
							   angleInDeg, vertAngleInDeg, magCompassHeadingInDeg]];
		*/
		double relativeDirectionToSite =  magCompassHeadingInDeg * (M_PI / 180.) - directionToSite;
		if (relativeDirectionToSite < (-M_PI / 2.0)) {
			relativeDirectionToSite = (-M_PI / 2.0); 
		}
		
		if (relativeDirectionToSite > (M_PI / 2.0)) {
			relativeDirectionToSite = (M_PI / 2.0); 
		}
		
		double relativeVertAngleToSite = vertAngleToSite - vertAngle;
		
		UIView *markerView = [overlayGraphicViews objectAtIndex:i];
		CGPoint overlayCenter = [markerView center];
		overlayCenter.y = 240.0 - 537.8 * sin(relativeVertAngleToSite);    
		overlayCenter.x = 160.0 - 497.8 * sin(relativeDirectionToSite);
		[markerView setCenter:overlayCenter];  
		
		//    NSLog(@"center = %@", NSStringFromCGPoint(overlayCenter));
		markerView.transform = CGAffineTransformMakeRotation(angle);
	}
}

#pragma mark UIAccelerometerDelegate
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration;
{
    vertAngle = atan2(acceleration.y, acceleration.z) + M_PI/2.0;
    vertAngleInDeg = vertAngle * 180.0f/M_PI;
    
    angle = -atan2(acceleration.y, acceleration.x) - M_PI/2.0;
    angleInDeg = angle * 180.0f/M_PI;
    [self updateUI];
}

#pragma mark CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading;
{
    magCompassHeadingInDeg = [newHeading magneticHeading];
    [self updateUI];
}

- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation;
{
    NSLog(@"%@ %s toLocation:%@ fromLocation:%@", self, _cmd, newLocation, oldLocation);
    
    [self setCurrentLocation:newLocation];
    [self updateUI];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

@synthesize currentLocation;

- (void)dealloc {
    [[UIAccelerometer sharedAccelerometer] setDelegate:nil];
    [locationManager stopUpdatingHeading]; 
    
    [currentLocation release]; currentLocation = nil;
    [locationManager release]; locationManager = nil;
    [anglesLabel release]; anglesLabel = nil;
//    [overlayGraphicView release]; overlayGraphicView = nil;
    [super dealloc];
}

@end





/*
 // The designated initializer. Override to perform setup that is required before the view is loaded.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */


/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */


/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */
